import * as usersService from '../services/users';

export default {
  namespace : 'users',
  state : {
    list: [],
    total: null,
    page: null
  },
  reducers : {
    save(state,action) {
      return Object.assign(state,action.payload)
    }
  },
  effects : {
    *fetch({
      payload: {
        page = 1
      }
    }, {call, put}) {
      const {data, headers} = yield call(usersService.fetch, {page});
      yield put({
        type: 'save',
        payload: {
          list:data.list,
          total: parseInt(data.total, 10),
          page: parseInt(data.page, 10),
        }
      });
    },
    *remove({payload:id},{call,put}){
      yield call(usersService.remove,id);
      // const page = yield select(state=>state.users.page);
      // yield put({type:'fetch',payload:{page}})
      yield put({type:'reload'})
    },
    *patch({payload:{id,values}},{call,put}){
      yield call(usersService.patch,id,values);
      // const page = yield select(state=>state.users.page);
      // yield put({type:'fetch',payload:{page}})
      yield put({type:'reload'})
    },
    *create({payload:values},{call,put}){
      yield call(usersService.create,values);
      yield put({type:'reload'})
    },
    *reload(action,{put,select}){
      const page = yield select(state=>state.users.page);
      yield put({type:'fetch',payload:{page}})
    }
  },
  subscriptions : {
    setup({dispatch, history}) {
      return history.listen(({pathname, query}) => {
        if (pathname === '/users') {
          dispatch({type: 'fetch', payload: query});
        }
      });
    }
  }
};
